package com.crm.manager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.common.core.domain.entity.SysUser;
import com.crm.common.exception.base.BaseException;
import com.crm.manager.domain.*;
import com.crm.manager.domain.dto.BatchDTO;
import com.crm.manager.domain.dto.BusinessDTO;
import com.crm.manager.domain.dto.BusinessPageDTO;
import com.crm.manager.domain.vo.BusinessVO;
import com.crm.manager.domain.vo.PageVO;
import com.crm.manager.mapper.BusinessDetailMapper;
import com.crm.manager.mapper.BusinessMapper;
import com.crm.manager.mapper.BusinessRecordMapper;
import com.crm.manager.mapper.ContractMapper;
import com.crm.manager.service.BusinessService;
import com.crm.manager.utils.BaseContext;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {

    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private BusinessRecordMapper businessRecordMapper;
    //把合同的代码也写到这里面
    @Autowired
    private BusinessDetailMapper businessDetailMapper;
    @Autowired
    private ContractMapper contractMapper;

    /**
     * 增加
     * @param business
     */
    @Override
    public void add(Business business) {
        business.setCreateBy(BaseContext.getUserName());
        business.setCreateTime(LocalDateTime.now());
        business.setOwnerId(BaseContext.getUserId().intValue());
        business.setOwner(BaseContext.getUserName());
        business.setStatus(Business.TO_BE_FOLLOW_UP);
        save(business);
    }

    /**
     * 分页查询
     */
    @Override
    public PageVO pageQuery(BusinessPageDTO dto) {
        PageVO pageVO = new PageVO();
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<Business> wrapper = new LambdaQueryWrapper<>();
        if (dto.getId() != null) {
            wrapper.like(Business::getId, dto.getId());
        }
        if (dto.getPhone() != null) {
            wrapper.like(Business::getPhone, dto.getPhone());
        }
        if (dto.getName() != null) {
            wrapper.like(Business::getName, dto.getName());
        }
        if (dto.getOwner() != null) {
            wrapper.like(Business::getOwner, dto.getOwner());
        }
        //1和2是正常状态，3是在垃圾池，所以这里最多只展示1和2
        if (dto.getStatus() != null) {
            wrapper.eq(Business::getStatus, dto.getStatus());
        } else {
            wrapper.in(Business::getStatus, Business.TO_BE_FOLLOW_UP, Business.FOLLOWING_UP);
        }
        if (dto.getBeginCreateTime() != null && dto.getEndCreateTime() != null) {
            wrapper.between(Business::getCreateTime, dto.getBeginCreateTime(), dto.getBeginCreateTime());
        }
        //transfer必须是0
        wrapper.eq(Business::getTransfer, "0");
        Page<Business> list = (Page<Business>) list(wrapper);
        pageVO.setTotal(list.getTotal());
        pageVO.setRows(list.getResult());
        return pageVO;
    }

    /**
     * 查询一个商机（客户）信息
     * @param id
     * @return
     */
    @Override
    public BusinessVO getBusinessDetail(Integer id) {
        return businessMapper.getBusinessDetail(id);
    }

    /**
     * 跟进时，触发的存储逻辑---存detail，存跟进记录，更新基础表
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public void addRecord(BusinessDTO dto) {
        BusinessDetail businessDetail = new BusinessDetail();
        BusinessRecord businessRecord = new BusinessRecord();
        Business business = new Business();
        //记录信息
        BeanUtils.copyProperties(dto, businessRecord);
        businessRecord.setBusinessId(Integer.parseInt(dto.getBusinessId()));
        businessRecord.setCreateBy(BaseContext.getUserName());
        businessRecord.setCreateTime(LocalDateTime.now());
        //更新基础信息
        BeanUtils.copyProperties(dto, business);
        business.setId(Integer.parseInt(dto.getBusinessId()));
        business.setStatus(Business.FOLLOWING_UP);
        business.setUpdateTime(LocalDateTime.now());
        business.setUpdateBy(BaseContext.getUserName());

        //详情信息
        BeanUtils.copyProperties(dto, businessDetail);
        businessDetail.setBusinessId(Integer.parseInt(dto.getBusinessId()));

        //保存前，先查数据库是否有business-detail数据，有的话更新，没有才新增
        //根据business_id去查
        BusinessDetail detail = businessDetailMapper.selectOne(Wrappers.<BusinessDetail>lambdaQuery()
                .eq(BusinessDetail::getBusinessId, Integer.parseInt(dto.getBusinessId())));

        if (detail == null) {
            businessDetailMapper.insert(businessDetail);
        } else {
            businessDetailMapper.update(businessDetail, Wrappers.<BusinessDetail>lambdaQuery()
                .eq(BusinessDetail::getBusinessId, Integer.parseInt(dto.getBusinessId())));
        }

        //business直接更新
        businessMapper.updateById(business);
        //businessRecord直接新增
        businessRecordMapper.insert(businessRecord);
    }

    /**
     * 查询商机的跟踪记录
     * @param businessId
     * @return
     */
    @Override
    public List<BusinessRecord> getRecordListById(Integer businessId) {
        return businessRecordMapper.selectList(Wrappers.<BusinessRecord>lambdaQuery().eq(BusinessRecord::getBusinessId, businessId));
    }

    /**
     * 放入公海，其实就是改个状态
     */
    @Override
    public void moveToPool(Integer id, String reason) {
        Business business = getById(id);
        business.setStatus(Business.POOL);
        business.setInPoolReason(reason);
        business.setUpdateBy(BaseContext.getUserName());
        business.setUpdateTime(LocalDateTime.now());
        businessMapper.updateById(business);
    }

    /**
     * 公海的分页查询
     */
    @Override
    public PageVO poolPageQuery(BusinessPageDTO dto) {
        PageVO pageVO = new PageVO();
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<Business> wrapper = new LambdaQueryWrapper<>();
        if (dto.getId() != null) {
            wrapper.like(Business::getId, dto.getId());
        }
        if (dto.getPhone() != null) {
            wrapper.like(Business::getPhone, dto.getPhone());
        }
        if (dto.getName() != null) {
            wrapper.like(Business::getName, dto.getName());
        }
        if (dto.getSubject() != null) {
            wrapper.eq(Business::getSubject, dto.getSubject());
        }
        //固定查3
        wrapper.in(Business::getStatus, Business.POOL);
        if (dto.getBeginCreateTime() != null && dto.getEndCreateTime() != null) {
            wrapper.between(Business::getCreateTime, dto.getBeginCreateTime(), dto.getBeginCreateTime());
        }
        //transfer必须是0
        wrapper.eq(Business::getTransfer, "0");
        Page<Business> list = (Page<Business>) list(wrapper);
        pageVO.setTotal(list.getTotal());
        pageVO.setRows(list.getResult());
        return pageVO;
    }

    /**
     * 从pool里面捞出来,支持批量
     */
    @Override
    public void gain(BatchDTO dto) {
        businessMapper.batchGain(dto.getIds(), dto.getUserId(), BaseContext.getUserName(), LocalDateTime.now());
    }

    /**
     *分配商机，支持批量
     * 分配就是把owner改为传过来的user
     *
     * @param dto dto.userId--分配给谁  dto.ids商机id
     */
    @Override
    public void assignment(BatchDTO dto) {
        //根据dto.userId查分配给谁
        SysUser user = businessMapper.queryUserById(dto.getUserId());
        businessMapper.batchAssignment(dto.getIds(), user.getUserId(), user.getUserName(),
                 BaseContext.getUserName(), LocalDateTime.now());
    }

    /**
     * 商机转化为合同。输入客户手机号，合同编号。查询合同编号，如果存在，就有问题，换一个合同编号
     * 不存在，就新建一个合同，数据由business转化来
     * @param id
     * @param map
     */
    @Override
    @Transactional
    public void changeContract(Integer id, Map map) {
        Contracts contract = businessDetailMapper.queryContract(map.get("contractNo").toString());
        if (contract != null) {
            throw new BaseException("合同编号重复");
        }
        //合同编号不重复的话，就新增合同，同时把对应的商机的transfer变成1
        businessMapper.updateTransfer(id);
        BusinessVO business = businessMapper.getBusinessDetail(id);
        contract = new Contracts();
        BeanUtils.copyProperties(business, contract);
        contract.setId(null);
        contract.setCreateBy(BaseContext.getUserName());
        contract.setCreateTime(LocalDateTime.now());
        contract.setContractNo(map.get("contractNo").toString());
        contract.setFileName(map.get("fileName").toString());
        contract.setBusinessId(id.toString());
        if (business.getCourseId() != null) {
            Course course = businessDetailMapper.getCourse(business.getCourseId());
            contract.setCoursePrice(BigDecimal.valueOf(course.getPrice()));
        }
        contractMapper.insert(contract);
    }

}
